<template>
  <div class="wangeditor">
    <Toolbar :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" style="border-bottom: 1px solid #ccc" />
    <Editor v-model="editorContent" :defaultConfig="editorConfig" :mode="mode" style="height: 500px; overflow-y: hidden"
      @onBlur="handleBlur" @onChange="handleChange" @onCreated="handleCreated" />
  </div>
</template>

<script setup lang="ts">
import { onMounted, shallowRef, onBeforeUnmount, computed } from "vue";
import "@wangeditor/editor/dist/css/style.css";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { formatToken, getToken } from "@/utils/auth";
import { message } from "@/utils/message";
import { thumbImg } from "@/utils/functions";
import { removeFileApi } from "@/api/user";

const emits = defineEmits(["update:content"]);
const props = defineProps({
  content: {
    type: String,
    default: ""
  },
  sure: {
    type: Boolean,
    default: true
  }
});

const mode = "default";
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
const toolbarConfig: any = { excludeKeys: "fullScreen" };
const editorConfig = { placeholder: "请输入内容...", MENU_CONF: {} };
const uploadApi = "/api/system/system/v2/file/upload";
const uploadImageList = [];

const editorContent = ref(props.content)

// 更多详细配置看 https://www.wangeditor.com/v5/menu-config.html#%E4%B8%8A%E4%BC%A0%E5%9B%BE%E7%89%87
editorConfig.MENU_CONF["uploadImage"] = {
  // 服务端上传地址，根据实际业务改写
  server: uploadApi,
  // form-data 的 fieldName，根据实际业务改写
  fieldName: "file",
  // base64LimitSize: 10 * 1024 * 1024, // 10M 以下插入 base64
  // 选择文件时的类型限制，根据实际业务改写
  allowedFileTypes: ["image/png", "image/jpg", "image/jpeg"],
  headers: {
    Authorization: formatToken(getToken().accessToken)
  },
  // 自定义插入图片
  customInsert(res: any, insertFn) {
    if (res.code !== 200) {
      message("上传失败", { type: "error" });
    } else {
      // 控制台打印thumbImg(res.result.fileUrl)
      console.log(res.result);
      uploadImageList.push({
        src: res.result
      });
      insertFn(thumbImg(res.result));
    }
  }
};
editorConfig.MENU_CONF["uploadVideo"] = {
  // 服务端上传地址，根据实际业务改写
  server: uploadApi,
  // form-data 的 fieldName，根据实际业务改写
  fieldName: "file",
  // 选择文件时的类型限制，根据实际业务改写
  headers: {
    Authorization: formatToken(getToken().accessToken)
  },
  // 自定义插入图片
  customInsert(res: any, insertFn) {
    if (res.code !== 200) {
      message("上传失败", { type: "error" });
    } else {
      insertFn(res.result.fileUrl);
    }
  }
};

const handleCreated = editor => {
  // 记录 editor 实例，重要！
  editorRef.value = editor;
};

onMounted(() => {
  // content.value = "dsd"
});
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  console.log("onBeforeUnmount");
  //接收父组件参数sure,默认为false,父组件点击确定则为true
  console.log("是否点击确定", props.sure);
  // 遍历取出uploadImageList中的url
  let urlList = uploadImageList.map(item => item.src);
  // 遍历取出编辑器中的图片
  let editorImageList = editor
    .getElemsByType("image")
    .map(item => item.src.split("?")[0]);
  console.log("上传的所有图片", urlList);
  console.log("当前编辑器的所有图片", editorImageList);
  if (props.sure) {
    // 对比，如果urlList不在editorImageList中，则使用removeFileApi接口删除
    urlList.forEach(element => {
      if (!editorImageList.includes(element)) {
        console.log("图片未上传", element);
        removeFileApi({
          fileUrl: element,
          osType: "qiniu"
        }).then(res => {
          console.log("删除图片", element, res);
        });
      }
    });
  } else {
    // 使用removeFileApi接口删除urlList中所有图片
    urlList.forEach(element => {
      removeFileApi({
        fileUrl: element,
        osType: "qiniu"
      }).then(res => {
        console.log("删除图片", element, res);
      });
    });
  }
  editor.destroy();
});

const handleBlur = () => {
  emits("update:content", editorContent.value);
}

const handleChange = () => {
  emits("update:content", editorContent.value);
}

</script>

<style scoped></style>
